<template>
  <div class="playedu-tree">
    <div
      :class="['mb-8', 'category-label', { active: selectKey.length === 0 }]"
      @click="onSelect([], '')"
    >
      <div class="j-b-flex">
        <span>全部{{ text }}</span>
      </div>
    </div>
    <a-tree
      :selectedKeys="selectKey"
      :treeData="treeData"
      :switcherIcon="switcherIcon"
      @select="onSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, h } from "vue";
import { Tree as ATree } from "ant-design-vue";
import { adminRole } from "../../api/index";

interface Option {
  key: string | number;
  title: any;
  children: any[];
}

interface Props {
  refresh: boolean;
  roleDelSuccess: boolean;
  type: string;
  text: string;
  onUpdate: (keys: any[], title: string, isSuper: boolean) => void;
}

const props = defineProps<Props>();

const treeData = ref<Option[]>([]);
const loading = ref<boolean>(true);
const selectKey = ref<any[]>([]);
const superId = ref(0);

// 切换器图标
const switcherIcon = h("i", { class: "iconfont icon-icon-fold c-gray" });

// 监听roleDelSuccess变化
watch(() => props.roleDelSuccess, () => {
  onSelect([], "");
});

// 监听refresh变化
watch(() => props.refresh, async () => {
  await loadTreeData();
}, { immediate: true });

// 加载树数据
async function loadTreeData() {
  try {
    const res: any = await adminRole.adminRoleList();
    const adminrole = res.data;
    let superIdValue = 0;
    
    if (adminrole.length > 0) {
      const new_arr: Option[] = [];
      for (let i = 0; i < adminrole.length; i++) {
        new_arr.push({
          title: adminrole[i].name,
          key: adminrole[i].id,
          children: [],
        });
        if (adminrole[i].slug === "super-role") {
          superIdValue = adminrole[i].id;
        }
      }
      treeData.value = new_arr;
    }
    superId.value = superIdValue;
  } catch (error) {
    console.error("加载角色树数据失败:", error);
  } finally {
    loading.value = false;
  }
}

// 选择处理
function onSelect(selectedKeys: any[], info: any) {
  let label = "全部" + props.text;
  if (info && info.node) {
    label = info.node.title;
  }
  let isSuper = false;
  if (selectedKeys[0] === superId.value && superId.value !== 0) {
    isSuper = true;
  }
  props.onUpdate(selectedKeys, label, isSuper);
  selectKey.value = selectedKeys;
}
</script>

<style scoped>

</style>